package cn.easyutil.project.web.handler;

import cn.easyutil.util.javaUtil.JsonUtil;
import cn.easyutil.util.javaUtil.LoggerUtil;
import cn.easyutil.project.web.advice.ResponseOutAdvice;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.easyutil.project.web.util.RequestPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired(required = false)
    private ResponseOutAdvice responseOutAdvice;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HttpServletResponse rs = ((ServletServerHttpResponse) response).getServletResponse();
        if(responseOutAdvice == null){
            responseOutAdvice = new DefaultResponseOutAdvice();
        }
        Class<?> type = returnType.getMethod().getReturnType();
        Object obj = responseOutAdvice.process(body,type, RequestPool.get(),rs);
        LoggerUtil.info(this.getClass(),"接口【"+ RequestPool.get().getRequestURI()+"】的响应数据为:"+ JsonUtil.beanToJson(obj));
        return obj;
    }
}